package com.fa4j.demo.book.controller;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.Page;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.demo.book.model.Book;
import com.fa4j.demo.book.model.BookCreateCmd;
import com.fa4j.demo.book.model.BookModifyCmd;
import com.fa4j.demo.book.model.BookQuery;
import com.fa4j.demo.book.repository.BookRepository;
import com.fa4j.demo.book.service.BookService;
import com.fa4j.system.login.util.LoginUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 示例书 Web接口
 *
 * @since 2025-09-01 18:44:28
 */
@RestController
@RequestMapping("demo/book")
@RequiredArgsConstructor
public class BookController {

    private final BookService bookService;
    private final BookRepository bookRepository;

    @GetMapping("page")
    @ApiMethod(name = "示例书分页查询", type = AppType.MANAGE)
    public Page<Book> page(BookQuery query) {
        return bookRepository.queryPage(query);
    }

    @GetMapping("{id}")
    @ApiMethod(name = "示例书详情查询", type = AppType.MANAGE)
    public Book detail(@PathVariable Integer id) {
        return bookRepository.findById(id)
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("示例书"));
    }

    @PostMapping
    @ApiMethod(name = "示例书创建", type = AppType.MANAGE)
    public Book create(@Valid @RequestBody BookCreateCmd cmd) {
        return bookService.create(cmd);
    }

    @PatchMapping
    @ApiMethod(name = "示例书编辑", type = AppType.MANAGE)
    public Book modify(@Valid @RequestBody BookModifyCmd cmd) {
        return bookService.modify(cmd);
    }

    @DeleteMapping("{id}")
    @ApiMethod(name = "示例书删除", type = AppType.MANAGE)
    public Book remove(@PathVariable Integer id) {
        return bookService.remove(RemoveCmd.of(id, LoginUtil.getAccountId()));
    }

}
